package service

import (
	"encoding/json"
	"fmt"
	"harbor/src/configs"
	"harbor/src/models"
	"io/ioutil"
	"reflect"
	"strconv"
)
//根据project获取到repository列表
func GetRepositories(project []models.Proj,harbor_url string,) []models.Repository{
	var ret []models.Repository
	repositories := make([]models.Repository,0)
	for _,reposi:=range project{
		if reposi.Name=="claim-endcase"||reposi.Name=="claim-register"{
			continue
		}
		//api:https://10.111.80.2/api/repositories?project_id=92
		resp_images,_:=configs.HttpInit().Get("https://"+harbor_url+"/api/repositories?project_id="+strconv.Itoa(reposi.Id))
		resp_images_body,_:=ioutil.ReadAll(resp_images.Body)
		defer resp_images.Body.Close()
		//返回序列化成image结构切片
		json.Unmarshal(resp_images_body,&ret)
		for _ , v := range ret {
			if ok:=reflect.DeepEqual(v, models.Repository{});!ok{
				repositories = append(repositories, v)
			}
		}
	}
	return repositories
}
//根据所有的repository获取到tag和镜像名字，并进行拼接，获取到imagename:tag,pushtime的struct切片
func GetImages(repositories []models.Repository,harbor_rul string) []models.Image_tag{
	//获取镜像tag，拼接完整镜像
	//api https://10.111.80.2/api/repositories/images_name/tags
	images :=make([]models.Image_tag,0)
	//镜像最终存的模式，images+tag, pushtime
	var images_tag []models.Image_tag
	for _,image := range repositories{
		LOOP:
		resp_images,_:=configs.HttpInit().Get("https://"+harbor_rul+"/api/repositories/"+image.Name+"/tags")
		resp_images_body,_:=ioutil.ReadAll(resp_images.Body)
		err:=json.Unmarshal(resp_images_body,&images_tag)
		if err!=nil{
			fmt.Println("http重试","https://"+harbor_rul+"/api/repositories/"+image.Name+"/tags",err)
			goto LOOP
		}
		defer resp_images.Body.Close()
		for _,v := range images_tag {
			if v.Size==0||v.Name==""{
				continue
			}
			ret:=models.Image_tag{
				Name: image.Name+":"+v.Name,
				Digest: v.Digest,
				Size: v.Size,
			}
			images = append(images,ret)
		}
	}
	return images
}

